<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-angle-left" @click="goBack"></i>
      <p>交易记录</p>
      <i class="fa fa-filter" @click="showFilterDialog"></i>
    </header>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <select v-model="filterType" @change="applyFilter">
        <option value="">全部类型</option>
        <option value="RECHARGE">充值</option>
        <option value="WITHDRAW">提现</option>
        <option value="PAYMENT">支付</option>
        <option value="REFUND">退款</option>
        <option value="FREEZE">冻结</option>
        <option value="RECEIPT">收款</option>
        <option value="UNFREEZE">解冻</option>
      </select>
    </div>

    <!-- 交易列表 -->
    <div class="transaction-list">
      <div v-if="loading" class="loading">
        <i class="fa fa-spinner fa-spin"></i>
        <span>加载中...</span>
      </div>

      <div v-else-if="transactions.length === 0" class="empty">
        <i class="fa fa-inbox"></i>
        <p>暂无交易记录</p>
      </div>

      <div
        v-else
        v-for="transaction in transactions"
        :key="transaction.id"
        class="transaction-item"
      >
        <div class="transaction-icon">
          <i :class="getTypeIcon(transaction.type)"></i>
        </div>
        <div class="transaction-info">
          <div class="transaction-title">{{ getTypeText(transaction.type) }}</div>
          <div class="transaction-time">{{ formatTime(transaction.createdAt) }}</div>
          <div class="transaction-status" :class="getStatusClass(transaction.status)">
            {{ getStatusText(transaction.status) }}
          </div>
        </div>
        <div class="transaction-amount" :class="getAmountClass(transaction.type)">
          {{ getAmountPrefix(transaction.type) }}¥{{ formatTransactionAmount(transaction.amount, transaction.type) }}
        </div>
      </div>

      <!-- 加载更多 -->
      <div v-if="hasMore && !loading" class="load-more" @click="loadMore">
        <span>加载更多</span>
        <i class="fa fa-angle-down"></i>
      </div>

      <div v-if="!hasMore && transactions.length > 0" class="no-more">
        没有更多了
      </div>
    </div>

    <!-- 筛选对话框 -->
    <div class="modal" v-if="filterDialogVisible" @click="closeFilterDialog">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>筛选条件</h3>
          <i class="fa fa-times" @click="closeFilterDialog"></i>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>交易类型</label>
            <select v-model="tempFilterType">
              <option value="">全部类型</option>
              <option value="RECHARGE">充值</option>
              <option value="WITHDRAW">提现</option>
              <option value="PAYMENT">支付</option>
              <option value="REFUND">退款</option>
              <option value="FREEZE">冻结</option>
              <option value="UNFREEZE">解冻</option>
            </select>
          </div>
          <div class="form-group">
            <label>时间范围</label>
            <div class="date-range">
              <input type="date" v-model="tempStartDate" />
              <span>至</span>
              <input type="date" v-model="tempEndDate" />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="resetFilter">重置</button>
          <button class="confirm-btn" @click="confirmFilter">确定</button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { walletAPI } from '@/api/wallet.js';
import { userAPI } from '@/api/user.js';

const router = useRouter();

// 交易列表
const transactions = ref([]);
const loading = ref(false);
const currentPage = ref(0);
const pageSize = ref(20);
const totalPages = ref(0);
const walletId = ref(null);

// 筛选条件
const filterType = ref('');
const startDate = ref('');
const endDate = ref('');

// 筛选对话框
const filterDialogVisible = ref(false);
const tempFilterType = ref('');
const tempStartDate = ref('');
const tempEndDate = ref('');

// 是否有更多数据
const hasMore = computed(() => {
  return currentPage.value < totalPages.value - 1;
});

// 获取当前用户ID
const getCurrentUserId = async () => {
  try {
    // 使用getSessionStorage工具函数获取userId（自动处理JSON.parse）
    const { getSessionStorage } = await import('@/common.js');
    const userId = getSessionStorage('userId');
    return userId ? parseInt(userId) : null;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
};

// 获取钱包ID
const fetchWalletId = async () => {
  const userId = await getCurrentUserId();
  if (!userId) {
    alert('请先登录');
    router.push('/login');
    return;
  }

  try {
    const response = await walletAPI.getBalance(userId);
    if (response.data && response.data.success) {
      walletId.value = response.data.data.walletId;
    } else if (response.data && response.data.walletId) {
      walletId.value = response.data.walletId;
    } else {
      throw new Error('获取钱包信息失败');
    }
  } catch (error) {
    console.error('获取钱包ID失败:', error);
    alert('获取钱包信息失败，请先进行充值操作');
  }
};

// 加载交易记录
const loadTransactions = async (page = 0, append = false) => {
  if (!walletId.value) {
    await fetchWalletId();
    if (!walletId.value) return;
  }

  loading.value = true;

  try {
    let response;

    console.log('开始加载交易记录，walletId:', walletId.value, 'page:', page);

    // 根据筛选条件选择不同的API
    if (startDate.value && endDate.value) {
      // 按时间范围查询
      const startTime = new Date(startDate.value).toISOString();
      const endTime = new Date(endDate.value + 'T23:59:59').toISOString();
      console.log('按时间查询:', startTime, endTime);
      response = await walletAPI.getTransactionsByTimeRange(
        walletId.value,
        startTime,
        endTime,
        page,
        pageSize.value
      );
    } else if (filterType.value) {
      // 按类型查询
      console.log('按类型查询:', filterType.value);
      response = await walletAPI.getTransactionsByType(
        walletId.value,
        filterType.value,
        page,
        pageSize.value
      );
    } else {
      // 查询全部
      console.log('查询全部交易记录');
      response = await walletAPI.getTransactions(
        walletId.value,
        page,
        pageSize.value
      );
    }

    console.log('交易记录API响应:', response);

    if (response.data && response.data.success) {
      const pageData = response.data.data;
      console.log('交易记录数据（success格式）:', pageData);
      if (append) {
        transactions.value = [...transactions.value, ...pageData.content];
      } else {
        transactions.value = pageData.content;
      }
      currentPage.value = pageData.number;
      totalPages.value = pageData.totalPages;
    } else if (response.data && response.data.content) {
      const pageData = response.data;
      console.log('交易记录数据（直接格式）:', pageData);
      if (append) {
        transactions.value = [...transactions.value, ...pageData.content];
      } else {
        transactions.value = pageData.content;
      }
      currentPage.value = pageData.number;
      totalPages.value = pageData.totalPages;
    } else {
      console.warn('未知的响应格式:', response.data);
    }

    console.log('最终交易记录数量:', transactions.value.length);
  } catch (error) {
    console.error('获取交易记录失败:', error);
    console.error('错误详情:', error.response);
    alert('获取交易记录失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    loadTransactions(currentPage.value + 1, true);
  }
};

// 应用筛选
const applyFilter = () => {
  currentPage.value = 0;
  loadTransactions();
};

// 显示筛选对话框
const showFilterDialog = () => {
  tempFilterType.value = filterType.value;
  tempStartDate.value = startDate.value;
  tempEndDate.value = endDate.value;
  filterDialogVisible.value = true;
};

// 关闭筛选对话框
const closeFilterDialog = () => {
  filterDialogVisible.value = false;
};

// 确认筛选
const confirmFilter = () => {
  filterType.value = tempFilterType.value;
  startDate.value = tempStartDate.value;
  endDate.value = tempEndDate.value;
  closeFilterDialog();
  applyFilter();
};

// 重置筛选
const resetFilter = () => {
  tempFilterType.value = '';
  tempStartDate.value = '';
  tempEndDate.value = '';
};

// 获取交易类型图标
const getTypeIcon = (type) => {
  const iconMap = {
    RECHARGE: 'fa fa-arrow-down',
    WITHDRAW: 'fa fa-arrow-up',
    PAYMENT: 'fa fa-shopping-cart',
    REFUND: 'fa fa-undo',
    FREEZE: 'fa fa-lock',
    RECEIPT: 'fa fa-lock',
    UNFREEZE: 'fa fa-unlock'
  };
  return iconMap[type] || 'fa fa-exchange-alt';
};

// 获取交易类型文本
const getTypeText = (type) => {
  const textMap = {
    RECHARGE: '充值',
    WITHDRAW: '提现',
    PAYMENT: '支付',
    REFUND: '退款',
    FREEZE: '冻结',
    RECEIPT: '冻结',
    UNFREEZE: '解冻'
  };
  return textMap[type] || '其他';
};

// 获取状态样式类
const getStatusClass = (status) => {
  const classMap = {
    SUCCESS: 'status-success',
    PENDING: 'status-pending',
    FAILED: 'status-failed'
  };
  return classMap[status] || '';
};

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    SUCCESS: '成功',
    PENDING: '处理中',
    FAILED: '失败'
  };
  return textMap[status] || '未知';
};

// 获取金额样式类
const getAmountClass = (type) => {
  return ['RECHARGE', 'REFUND', 'UNFREEZE'].includes(type)
    ? 'amount-income'
    : 'amount-expense';
};

// 获取金额前缀
const getAmountPrefix = (type) => {
  return ['RECHARGE', 'REFUND', 'UNFREEZE'].includes(type) ? '+' : '';
};

// 格式化交易金额（冻结/解冻不显示负号）
const formatTransactionAmount = (amount, type) => {
  if (amount === null || amount === undefined) return '0.00';
  const num = parseFloat(amount);
  // 冻结/收款类型使用绝对值
  if (['FREEZE', 'RECEIPT'].includes(type)) {
    return Math.abs(num).toFixed(2);
  }
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0.00';
  const num = parseFloat(price);
  return isNaN(num) ? '0.00' : num.toFixed(2);
};

// 格式化时间
const formatTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 返回
const goBack = () => {
  router.back();
};

onMounted(async () => {
  await fetchWalletId();
  if (walletId.value) {
    loadTransactions();
  }
});
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
}

.wrapper header i {
  font-size: 6vw;
  cursor: pointer;
}

/****************** 筛选栏 ******************/
.filter-bar {
  margin-top: 12vw;
  padding: 3vw 4vw;
  background: white;
  border-bottom: 1px solid #f0f0f0;
}

.filter-bar select {
  width: 100%;
  height: 9vw;
  border: 1px solid #ddd;
  border-radius: 1vw;
  padding: 0 3vw;
  font-size: 3.5vw;
  background: white;
}

/****************** 交易列表 ******************/
.transaction-list {
  padding: 2vw 0;
}

.loading,
.empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10vw 0;
  color: #999;
}

.loading i {
  font-size: 8vw;
  margin-bottom: 2vw;
}

.empty i {
  font-size: 15vw;
  margin-bottom: 3vw;
}

.empty p {
  font-size: 4vw;
}

.transaction-item {
  background: white;
  margin: 2vw 4vw;
  padding: 4vw;
  border-radius: 2vw;
  display: flex;
  align-items: center;
  gap: 3vw;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.transaction-icon {
  width: 10vw;
  height: 10vw;
  border-radius: 50%;
  background: #f0f8ff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.transaction-icon i {
  font-size: 5vw;
  color: #0097ff;
}

.transaction-info {
  flex: 1;
  min-width: 0;
}

.transaction-title {
  font-size: 4vw;
  color: #333;
  font-weight: bold;
  margin-bottom: 1vw;
}

.transaction-time {
  font-size: 3vw;
  color: #999;
  margin-bottom: 1vw;
}

.transaction-status {
  display: inline-block;
  font-size: 2.8vw;
  padding: 0.5vw 2vw;
  border-radius: 1vw;
}

.status-success {
  background: #e6f7ed;
  color: #52c41a;
}

.status-pending {
  background: #fff7e6;
  color: #ff8c00;
}

.status-failed {
  background: #fff1f0;
  color: #ff4d4f;
}

.transaction-amount {
  font-size: 4.5vw;
  font-weight: bold;
  white-space: nowrap;
}

.amount-income {
  color: #52c41a;
}

.amount-expense {
  color: #ff4d4f;
}

.load-more {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4vw;
  color: #0097ff;
  font-size: 3.5vw;
  cursor: pointer;
  gap: 1vw;
}

.load-more:hover {
  opacity: 0.8;
}

.no-more {
  text-align: center;
  padding: 4vw;
  color: #999;
  font-size: 3.5vw;
}

/****************** 对话框 ******************/
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.modal-content {
  background: white;
  width: 80%;
  max-width: 500px;
  border-radius: 2vw;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4vw;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  font-size: 4.5vw;
  color: #333;
  margin: 0;
}

.modal-header i {
  font-size: 5vw;
  color: #999;
  cursor: pointer;
}

.modal-body {
  padding: 4vw;
}

.form-group {
  margin-bottom: 4vw;
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-group label {
  display: block;
  font-size: 3.5vw;
  color: #666;
  margin-bottom: 2vw;
}

.form-group select {
  width: 100%;
  height: 10vw;
  border: 1px solid #ddd;
  border-radius: 1vw;
  padding: 0 3vw;
  font-size: 4vw;
  box-sizing: border-box;
  background: white;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.date-range input {
  flex: 1;
  height: 10vw;
  border: 1px solid #ddd;
  border-radius: 1vw;
  padding: 0 3vw;
  font-size: 3.5vw;
  box-sizing: border-box;
}

.date-range span {
  font-size: 3.5vw;
  color: #666;
}

.modal-footer {
  display: flex;
  gap: 3vw;
  padding: 4vw;
  border-top: 1px solid #f0f0f0;
}

.modal-footer button {
  flex: 1;
  height: 10vw;
  border: none;
  border-radius: 1vw;
  font-size: 4vw;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
}

.cancel-btn:hover {
  background: #e8e8e8;
}

.confirm-btn {
  background: #0097ff;
  color: white;
}

.confirm-btn:hover {
  background: #0086e6;
}
</style>
